package network;

import java.io.IOException;
import java.net.*;
//import java.net.DatagramPacket;
//import java.net.DatagramSocket;
//import java.net.InetAddress;
//import java.net.SocketException;
import java.util.Scanner;

public class UdpEchoClient {
    /**
     * 注意这种没有交换成功
    public static void main(String[] args) {
        int a = 10;
        int b = 20;
        swap(a,b);
        System.out.println(a);
        System.out.println(b);
    }
     注意这种没有交换成功
    public static void swap(int a,int b) {
        int tmp = a;
        a = b;
        b = tmp;
    }
    */

    private DatagramSocket socket = null;
    private String serverIP;
    private int serverPort;

    //客户端启动，需要知道服务器在哪(类似于需要知道 餐馆这个服务器具体的位置)
    public UdpEchoClient(String serverIP, int serverPort) throws SocketException {
        //对于客户端来说，不需要显式关联端口
        //不代表没有端口，而是系统自动分配空闲的端口
        socket = new DatagramSocket();
        this.serverIP = serverIP;
        this.serverPort = serverPort;
    }

    //客户端启动
    public void start() throws IOException {
        Scanner scanner = new Scanner(System.in);
        while(true) {
            System.out.print("-> ");
            String request = scanner.next();

            // 2. 把字符串构造成UDPpacket，并进行发送
            DatagramPacket requestPacket = new DatagramPacket(request.getBytes(), request.getBytes().length,
                    InetAddress.getByName(serverIP), serverPort);
            socket.send(requestPacket);
            // 3. 客户端尝试读取服务器返回的响应
            DatagramPacket responsePacket = new DatagramPacket(new byte[4096], 4096);
            socket.receive(responsePacket);
            // 4. 把响应结果转换成String 显示出来
            String  response = new String(responsePacket.getData(),0,responsePacket.getLength());
            System.out.printf("req: %s, resp: %s\n",request,response);
        }
    }

    public static void main(String[] args) throws IOException {
        UdpEchoClient udpEchoClient = new UdpEchoClient("127.0.0.1",9090);
        udpEchoClient.start();
    }
}
